package com.xfcy.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xfcy.blog.common.R;
import com.xfcy.blog.common.constant.SqlConstant;
import com.xfcy.blog.dto.RoleDTO;
import com.xfcy.blog.mapper.RoleMapper;
import com.xfcy.blog.entity.Role;
import com.xfcy.blog.mapper.RoleMenuMapper;
import com.xfcy.blog.service.RoleMenuService;
import com.xfcy.blog.service.RoleService;
import com.xfcy.blog.utils.BeanCopyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统管理-角色表 (Role)表服务实现类
 *
 * @author 晓风残月Lx
 * @since 2023-04-09 11:03:06
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    /**
     * 角色列表
     *
     * @param pageNo
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public R listRole(Integer pageNo, Integer pageSize, String name) {
        Page<Role> rolePage = baseMapper.selectPage(new Page<>(pageNo, pageSize), new QueryWrapper<Role>().eq(StringUtils.isNotBlank(name), SqlConstant.NAME, name));
        return R.success(rolePage);
    }

    /**
     * 添加角色
     * @param roleDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R createRole(RoleDTO roleDTO) {
        Role role = Role.builder().code(roleDTO.getCode())
                .name(roleDTO.getName())
                .remarks(roleDTO.getRemarks())
                .build();
        baseMapper.insert(role);
        roleMenuMapper.insertBatchByRole(roleDTO.getMenus(), role.getId());
        return R.success();
    }

    /**
     * 角色详情
     * @param roleId
     * @return
     */
    @Override
    public R queryRoleId(Integer roleId) {
        List<Integer> list = roleMenuMapper.queryRoleId(roleId);
        return R.success(list);
    }

    /**
     * 修改用户信息
     * @param roleDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateRole(RoleDTO roleDTO) {
        Role role = BeanCopyUtil.copyObject(roleDTO, Role.class);
        baseMapper.updateById(role);

        // 先删所有权限 再新增
        roleMenuMapper.deleteByRoleId(role.getId(), null);
        roleMenuMapper.insertBatchByRole(roleDTO.getMenus(), role.getId());
        return R.success("修改成功");

    }

    /**
     * 批量删除或删除角色
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R removeRoles(List<Integer> ids) {
        baseMapper.deleteBatchIds(ids);
        ids.forEach(id -> roleMenuMapper.deleteByRoleId(id, null));
        return R.success();
    }

}


